package com.bbs.toutiao.service.admin.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.bbs.toutiao.aspect.SysLog;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import com.bbs.toutiao.service.admin.UploadService;
import com.fasterxml.jackson.core.Base64Variant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 描述: 文件上传获取阿里云数据
 * 作者： zhangBin
 * 时间： 2023/9/30 13:11
 * 版本： 1.0
 */

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {


    @Value(value = "${sms.accessKeyId}")
    private String accessKeyId;

    @Value(value = "${sms.accessKeySecret}")
    private String accessKeySecret;

    @Value(value = "${sms.endpoint}")
    private String endpointId;

    @Value(value = "${sms.bucketName}")
    private String bucketName;

    @SysLog("管理员执行了阿里云OSS上传")
    @Override
    public Map<String, String> upload() {

        String endpoint = "sts.cn-hangzhou.aliyuncs.com";
        String roleArn = "acs:ram::1896371028057181:role/ramosstest";
        String roleSessionName = "yourRoleFile";
        // 设置临时访问凭证的有效时间为3600秒。
        Long durationSeconds = 3600L;
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setSysEndpoint(endpoint);
        request.setDurationSeconds(durationSeconds);
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            Map<String, String> map = new HashMap<>();
//            System.out.println(JSONUtil.toJsonStr(response));
            log.info("获取了阿里云临时凭证，过期时间：" + durationSeconds);
            map.put("AccessKeyId", response.getCredentials().getAccessKeyId());
            map.put("AccessKeySecret", response.getCredentials().getAccessKeySecret());
            map.put("SecurityToken", response.getCredentials().getSecurityToken());
            return map;
        } catch (ServerException e) {
            System.out.println(e + "");
            throw new BaseException(ExceptionEnum.SERVER_BUSY);
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
            throw new BaseException(ExceptionEnum.SERVER_BUSY);
        }
    }


    /**
     * 删除阿里云文件
     *
     * @param url
     */
    @SysLog("用户删除文件")
    @Override
    public int deleteFile(String url) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpointId, accessKeyId, accessKeySecret);


        try {
            boolean isExist = ossClient.doesObjectExist(bucketName, url);
            if (isExist) {
                // 删除文件，url是你要删除的文件在OSS中的完整路径。
                ossClient.deleteObject(bucketName, url);
                System.out.println("Delete object succeed");
                return 1;
            } else {
                return 0;
            }

        } catch (OSSException e) {
            System.out.println("Error deleting object: " + e.getMessage());
            throw new BaseException(ExceptionEnum.SERVER_BUSY);
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }

    /**
     * 批量删除
     * @param url
     * @return
     */

    @SysLog("用户批量删除了文件")
    @Override
    public int deleteAll(List<String> url) throws Exception {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpointId, accessKeyId, accessKeySecret);
        try {
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(url).withEncodingType("url"));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            for(String obj : deletedObjects) {
                String deleteObj =  URLDecoder.decode(obj, StandardCharsets.UTF_8);
                System.out.println(deleteObj);
            }
            return deletedObjects.size();
        } catch (OSSException e) {
            System.out.println("Error deleting object: " + e.getMessage());
            throw new BaseException(ExceptionEnum.SERVER_BUSY);
        }catch (IllegalArgumentException lle){
            System.out.println("Error deleting object: " + lle.getMessage());
            throw new Exception(lle);
        }
        finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }

    //

}
